var textArea

const Clipboard = {
	createTextArea(text) {
		textArea = document.createElement('input');
		textArea.value = text;
		textArea.readOnly = true
		textArea.style.position='absolute';
		textArea.style.top='0px';
		textArea.style.right='-9999px';
		textArea.style.zIndex = "-1000";
		document.body.appendChild(textArea);
	},
	selectText(textbox, startIndex, stopIndex) {
	    if (textbox.createTextRange) {//ie
	        const range = textbox.createTextRange();
	        range.collapse(true);
	        range.moveStart('character', startIndex);//起始光标
	        range.moveEnd('character', stopIndex - startIndex);//结束光标
	        range.select();//不兼容苹果
	    } else {//firefox/chrome
	        textbox.setSelectionRange(startIndex, stopIndex);
	        textbox.focus();
	    }
	},
	copyToClipboard() {
	    try{
	      if(document.execCommand("Copy")){
			uni.showToast({
				title: '复制成功',
				icon: 'success'
			})
	      }else{
			uni.showToast({
				title: '复制失败！请手动复制！',
				icon: 'none'
			})
	      }
	    }catch(err){
			uni.showToast({
				title: '复制失败！请手动复制！',
				icon: 'none'
			})
	    }
		textArea.blur();
	    document.body.removeChild(textArea);
	},
	copy(text) {
		let textString = text.toString();
        this.createTextArea(textString);
        this.selectText(textArea, 0, textString.length);
        this.copyToClipboard();
    }
}

export default Clipboard
